<!-- ace-editor -->
<template>
  <div :id="_d.id" class="ace-editor-main"></div>
</template>

<script setup>
	import { reactive, ref, watch, onMounted, useSlots } from 'vue'
	import {getId} from "/@/utils/Tools.js";

	const slots = useSlots();
	const emits = defineEmits(['update:modelValue'])

	const props = defineProps({
		modelValue: {
			type: String
		},
	})

	const _d = reactive({
		id: 'ace-editor-'+getId(),
	})

	watch(() => props.modelValue, () => {
		oAce.setValue(props.modelValue);
	})

	onMounted(() => {
		oAce.init();
	})

	// 编辑
  const oAce = {
    editor: null,
    timer: null,
    code: '',
    // 初始化Ace
    async init () {
      this.editor = ace.edit(_d.id);
      this.editor.session.setMode('ace/mode/javascript'); // 设置语言
      this.editor.setTheme('ace/theme/tomorrow'); // 设置主题
      this.editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true// 设置自动提示
      })
      this.editor.getSession().on('change', e => {
      	this.changeValue();
      })
    },
    // 设置ace-editor内容文本
    setValue (code) {
    	if(code != this.code) {
    		this.code = code;
    		this.editor.setValue(code, -1);
    	}
    },
    getValue () {
      return this.editor.getValue();
    },
    // 改变内容
    changeValue() {
    	clearTimeout(this.timer);
    	this.timer = setTimeout(() => {
    		let value = this.getValue();
    		this.code = value;
    		emits('update:modelValue', value);
    	}, 500);
    }
  }

</script>

<style lang="scss" scoped>
.ace-editor-main {
	height: 100%;
	min-height: 100px;
}
</style>